package com.calcgpa.core;

import java.io.IOException;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.protocol.HTTP;

public class HttpRequest {
	
	/**
	 * Execute a HTTP Get request and return the response value.
	 *
	 * @param url the request url
	 * @param queryString the query parameter, it can be null.
	 * @return the response html value using String.
	 * @throws IOException 
	 * @throws ClientProtocolException 
	 */
    public static String doGet(HttpClient httpClient, String url, String queryString) throws ClientProtocolException, IOException {
    	if (queryString == null || queryString == "") 
    		queryString = "";
    	else 
    		queryString = "?" + queryString;
    	HttpGet httpget = new HttpGet(url + queryString);
    	ResponseHandler<String> responseHandler = new BasicResponseHandler();
    	String responseBody = httpClient.execute(httpget, responseHandler);
    	httpget.abort();
    	return responseBody;
    }

	/**
	 * Execute a HTTP Pose request and return the response value.
	 *
	 * @param url the request url
	 * @param nvps the query parameter using the List of NameValuePair
	 * @return the response html value using String.
	 * @throws IOException 
	 * @throws ClientProtocolException 
	 */
    public static String doPost(HttpClient httpclient, String url, List <NameValuePair> nvps) throws ClientProtocolException, IOException {
    	HttpPost httppost = new HttpPost(url);
    	httppost.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));
        ResponseHandler<String> responseHandler = new BasicResponseHandler();
        String responseBody = httpclient.execute(httppost ,responseHandler);
        httppost.abort();
        return responseBody;
    }

	/**
	 * Execute a HTTP Pose request but not return the response value.
	 * For some special post.
	 * 
	 * @see com.calcgpa.core.HttpRequest#doPost(HttpClient, String, List)
	 */
    public static void doPostWithNoResponse(HttpClient httpclient, String url, List <NameValuePair> nvps) throws ClientProtocolException, IOException {
    	HttpPost httppost = new HttpPost(url);
    	httppost.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));
        httpclient.execute(httppost);
        httppost.abort();
    }
}
